// mtools.cpp
// mtools implementation
//
#include <time.h>
#include <stdio.h>
#include <sys/time.h>

#include <string.h>
#include <strings.h>

#include <sys/socket.h>
#include <arpa/inet.h>

#include "mlog.h"

#include "mtools.h"
char* CMTools::GetCurTime()
{
    time_t t;
    struct tm *now;
    time(&t);
    now = localtime(&t);

    static char time[30] = {0};
    sprintf(time, "%02d:%02d:%02d", now->tm_hour, now->tm_min, now->tm_sec);

    return time;
}

char* CMTools::GetCurDate()
{
    time_t t;
    struct tm *now;
    time(&t);
    now = localtime(&t);
    
    static char date[30] = {0};
    sprintf(date, "%04d-%02d-%02d", now->tm_year+1900, now->tm_mon+1, now->tm_mday);
    return date;
}

char* CMTools::GetCurDateTime()
{
    time_t t;
    struct tm *now;
    time(&t);
    now = localtime(&t);

    static char dt[50] = {0};
    //sprintf(dt, "%04d-%02d-%02d %02d:%02d:%02d", now->tm_year+1900, now->tm_mon+1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);
    strftime(dt, 49, "%F %X", now);
    return dt;
}

long CMTools::GetTick()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_usec;
}

int CMTools::GetPeerIpPort(int fd, char *ip, int &port)
{
    if (NULL == ip)
    {
        CMLog::Plog("IP = NULL, please alloc it");
        return -2;
    }

    bzero(ip, strlen(ip));
    socklen_t len;
    struct sockaddr_in sin = {0};
    if (getpeername(fd, (struct sockaddr*)&sin, &len) < 0)
    {
        CMLog::Plog("getpeername < 0");
        return -1;
    }

    inet_ntop(AF_INET, &sin.sin_addr, ip, strlen(ip));

    port = ntohs(sin.sin_port);

    CMLog::Plog("%d, %s:%d", fd, ip, port);

    return port;
}
// gethostname, gethostbyname
int CMTools::GetLocalIpPort(int fd, char *ip, int &port)
{
    // just hard code the server ip and port.
    //return -1;
    if (NULL == ip)
    {
        CMLog::Plog("IP = NULL, please alloc it");
        return -2;
    }

    bzero(ip, strlen(ip));
    socklen_t len;
    struct sockaddr_in sin = {0};
    if (getsockname(fd, (struct sockaddr*)&sin, &len) < 0)
    {
        CMLog::Plog("getsockname < 0");
        return -1;
    }

    inet_ntop(AF_INET, &sin.sin_addr, ip, strlen(ip));

    port = ntohs(sin.sin_port);

    CMLog::Plog("%d, %s:%d", fd, ip, port);

    return port;
}

